package com.wwj.service.impl;


import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.wwj.common.constant.MessageConstant;
import com.wwj.common.constant.StatusConstant;
import com.wwj.common.result.PageResult;
import com.wwj.mapper.CategoryMapper;
import com.wwj.mapper.SetmealMapper;
import com.wwj.pojo.dto.CategoryDTO;
import com.wwj.pojo.dto.CategoryPageQueryDTO;
import com.wwj.pojo.entity.Category;
import com.wwj.pojo.entity.Check;
import com.wwj.service.CategoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
@Slf4j
public class CategoryServiceImpl implements CategoryService {

    @Resource
    private CategoryMapper categoryMapper;

    @Resource
    private SetmealMapper setmealMapper;

    //新增分类
    @Override
    public void InsertCategory(CategoryDTO categoryDTO) {
        Category category=new Category();
        BeanUtils.copyProperties(categoryDTO,category);
        category.setStatus(StatusConstant.DISABLE);
        categoryMapper.InsertCategory(category);
    }

    //根据id删除分类
    @Override
    public void deleteById(Long id) {

        Category category=categoryMapper.selectById(id);
        if(category.getStatus()==StatusConstant.ENABLE){
            throw new RuntimeException(MessageConstant.STATUS_1);
        }


        //删除分类数据
        categoryMapper.deleteById(id);
    }


    //修改分类
    @Override
    public void updateCategory(CategoryDTO categoryDTO) {
        Category category=new Category();
        BeanUtils.copyProperties(categoryDTO,category);
        categoryMapper.update(category);
    }

    //分类分页查询
    @Override
    public PageResult pageQuery(CategoryPageQueryDTO categoryPageQueryDTO) {
        PageHelper.startPage(categoryPageQueryDTO.getPage(),categoryPageQueryDTO.getPageSize());
        Page<Category> page=categoryMapper.pageQuery(categoryPageQueryDTO);
        long total = page.getTotal();
        List<Category> result = page.getResult();
        return new PageResult(total, result);
    }



    //启用、禁用分类
    @Override
    public void updateByIdAndStatus(Integer status, Long id) {
        //查询当前分类是否关联了套餐，如果关联了就抛出业务异常
        Integer count = setmealMapper.countByCategoryId(id);
        if(count > 0){
            //当前分类下有套餐，不能禁用
            throw new RuntimeException(MessageConstant.CATEGORY_BE_RELATED_BY_SETMEAL);
        }
        Category category=Category.builder()
                .status(status)
                .id(id)
                .build();
        categoryMapper.update(category);
    }

    //查询启用的分类
    @Override
    public List<Category> list() {

        return categoryMapper.list();
    }

}
